package cool.tsy.emos.wx;

import cn.hutool.core.util.StrUtil;
import cool.tsy.emos.wx.constant.SystemConstants;
import cool.tsy.emos.wx.db.dao.SysConfigDao;
import cool.tsy.emos.wx.db.pojo.SysConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.lang.reflect.Field;
import java.util.List;

/**
 * @author: hongxuan.wang
 * @date: Created in 2021/9/23 12:01
 * @description: SpringBoot 应用入口
 * @mail: 1443424326@qq.com
 */
@EnableAsync
@SpringBootApplication
@Slf4j
@ServletComponentScan
public class RestApplication {

    private final SysConfigDao sysConfigDao;

    private final SystemConstants systemConstants;

    @Value("${emos.image-folder}")
    private String imageFolder;

    public RestApplication(SysConfigDao sysConfigDao, SystemConstants systemConstants) {
        this.sysConfigDao = sysConfigDao;
        this.systemConstants = systemConstants;
    }

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(RestApplication.class);
        ConfigurableEnvironment ctxEnvironment = ctx.getEnvironment();
        String port = ctxEnvironment.getProperty("server.port");
        String contextPath = ctxEnvironment.getProperty("server.servlet.context-path");
        contextPath = ObjectUtils.isEmpty(contextPath) ? "" : contextPath.replace("/", "");
        log.info("---------------------------------------------------");
        log.info("启动成功，dev访问地址：\thttp://127.0.0.1:{}/{}", port, contextPath);
        log.info("Swagger 访问地址：\thttp://127.0.0.1:{}/{}/swagger-ui.html", port, contextPath);
    }

    @PostConstruct
    public void init() {
        List<SysConfig> sysConfigList = sysConfigDao.selectAllParam();
        sysConfigList.forEach(item -> {
            String paramKey = item.getParamKey();
            paramKey = StrUtil.toCamelCase(paramKey);
            String paramValue = item.getParamValue();
            try {
                Field field = systemConstants.getClass().getDeclaredField(paramKey);
                field.set(systemConstants, paramValue);
            } catch (Exception ex) {
                log.error("执行异常", ex);
            }
        });
        new File(imageFolder).mkdirs();
    }
}
